import subprocess
import json
import os
import configparser
from pathlib import Path

class DeviceManager:
    def __init__(self):
        self.config = self._load_config()
        self.app_path = self.config.get('External', 'app_path')
        self.timeout = self.config.getint('Settings', 'timeout')
        self.encoding = self.config.get('Settings', 'encoding')
        self.current_device = None
        self.connected = False
        
        # 如果app_path为空，使用调试模式
        self.debug_mode = not bool(self.app_path)
        
        # 只在非调试模式下检查程序是否存在
        if not self.debug_mode and not os.path.exists(self.app_path):
            raise FileNotFoundError(f"找不到外部程序: {self.app_path}")

    def _load_config(self):
        """加载配置文件"""
        config = configparser.ConfigParser()
        config_path = Path(__file__).parent.parent / 'config.ini'
        
        if not config_path.exists():
            # 创建默认配置
            config['External'] = {
                'app_path': r"D:\读卡器\RFIDDemo3404_beta(1)\RFIDDemo3404_beta\RFIDDemo.exe"
            }
            config['Settings'] = {
                'timeout': '5000',
                'encoding': 'gbk'
            }
            # 保存默认配置
            with open(config_path, 'w', encoding='utf-8') as f:
                config.write(f)
        else:
            config.read(config_path, encoding='utf-8')
        
        return config

    def get_devices(self):
        """获取可用设备列表"""
        # 在调试模式下返回模拟设备列表
        if self.debug_mode:
            return [
                {'id': 'DEMO_DEVICE_1', 'name': '模拟设备1 (AA系列)'},
                {'id': 'DEMO_DEVICE_2', 'name': '模拟设备2 (AP系列)'}
            ]
            
        try:
            # 正常的设备列表获取逻辑
            result = subprocess.run([self.app_path, "--list"], 
                                 capture_output=True, 
                                 text=True,
                                 encoding='gbk')
            
            if result.returncode == 0:
                return self._parse_device_list(result.stdout)
            else:
                print(f"获取设备列表失败: {result.stderr}")
                return []
        except Exception as e:
            print(f"获取设备列表错误: {str(e)}")
            return []

    def connect_device(self, device_id):
        """连接指定设备"""
        # 在调试模式下，所有设备都能成功连接
        if self.debug_mode:
            self.current_device = device_id
            self.connected = True
            return True
            
        try:
            # 如果是调试设备，直接返回成功
            if device_id == 'DEBUG_DEVICE':
                self.current_device = device_id
                self.connected = True
                return True
                
            # 正常设备的连接逻辑
            result = subprocess.run([self.app_path, "--connect", str(device_id)],
                                 capture_output=True,
                                 text=True,
                                 encoding='gbk')
            
            if result.returncode == 0:
                self.current_device = device_id
                self.connected = True
                return True
            else:
                print(f"连接设备失败: {result.stderr}")
                return False
        except Exception as e:
            print(f"设备连接错误: {str(e)}")
            self.connected = False
            return False

    def disconnect_device(self):
        """断开当前设备连接"""
        try:
            if self.current_device:
                result = subprocess.run([self.app_path, "--disconnect", str(self.current_device)],
                                     capture_output=True,
                                     text=True,
                                     encoding='gbk')
                
                if result.returncode == 0:
                    self.current_device = None
                    self.connected = False
                    return True
                else:
                    print(f"断开设备失败: {result.stderr}")
                    return False
        except Exception as e:
            print(f"设备断开连接错误: {str(e)}")
            return False

    def is_connected(self):
        """检查设备是否已连接"""
        return self.connected

    def _parse_device_list(self, output):
        """解析设备列表输出
        这个方法需要根据实际的输出格式进行调整
        """
        try:
            # 这里需要根据实际的输出格式进行解析
            # 示例：假设输出是每行一个设备，格式为 "id:name"
            devices = []
            for line in output.strip().split('\n'):
                if line:
                    try:
                        device_id, name = line.strip().split(':')
                        devices.append({
                            'id': device_id.strip(),
                            'name': name.strip()
                        })
                    except ValueError:
                        print(f"无法解析设备信息: {line}")
                        continue
            return devices
        except Exception as e:
            print(f"解析设备列表错误: {str(e)}")
            return []

    def _execute_command(self, command, *args):
        """执行命令并返回结果"""
        try:
            full_command = [self.app_path, command] + list(args)
            result = subprocess.run(full_command,
                                 capture_output=True,
                                 text=True,
                                 encoding='gbk')
            return result
        except Exception as e:
            print(f"执行命令错误: {str(e)}")
            return None 